<?php
function upload($file, $setName, $usrName, $maxSize, $types, $path){
    if ($file['size'] > $maxSize || $file['size'] <= 0) {
        header("Location:/upload.html?param1=1");
        exit;
    }
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    if (!in_array($ext, $types)) {
        header("Location:/upload.html?param1=2");
        exit;
    }
    $filename = date('YmdHis').uniqid();
    $basename = $filename.'.'.$ext;
    //$basename = $file["name"];
    $dest = $path.'/'.$basename;
    echo "new name: " . $dest;
    $tmp = $file['tmp_name'];
    if(file_exists($dest)){
        header("Location:/upload.html?param1=3");
        exit;
    }
    if(move_uploaded_file($tmp, $dest)){
        $idDest = 'assets/index.js';
        writeIndex($dest, $setName, $usrName, $idDest);
        return $basename;
    }
}

function writeIndex($filepath, $setName, $usrName, $idDest){
    $indexFile = fopen($idDest, 'a');
    echo fwrite($indexFile, "arrFile.push(\"" . $filepath . "\");\n") . '<br>';
    echo fwrite($indexFile, "arrName.push(\"" . $setName . "\");\n") . '<br>';
    echo fwrite($indexFile, "arrNameUsr.push(\"" . $setName . " from " . $usrName . "\");\n") . '<br>';
    fclose($indexFile);
    return;
}

    $maxSize = 1024 * 1024 * 3;
    $types = ['jpg', 'jpeg', 'pjpeg', 'png', 'gif'];
    $path = 'assets/images/upload';
    $file = $_FILES['filename'];
    $setName = $_POST['puzzlename'];
    $usrName = $_POST['customname'];
    //exit;
    upload($file, $setName, $usrName, $maxSize, $types, $path);
    $randDate = rand();
    echo "<br>try rand date: " . strval($randDate);
    $newUrl = "Location:/index.html?date=" . strval($randDate);
    echo "<br>" . $newUrl;
    header($newUrl);
    exit;
?>